/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved. 
 */
function showWeek(week) {
    var weekStr = "无法解析";
    if (1 == week) {
        weekStr = "周一";
    } else if (2 == week) {
        weekStr = "周二";
    } else if (3 == week) {
        weekStr = "周三";
    } else if (4 == week) {
        weekStr = "周四";
    } else if (5 == week) {
        weekStr = "周五";
    } else if (6 == week) {
        weekStr = "周六";
    } else if (7 == week) {
        weekStr = "周日";
    }
    return weekStr;
}
function showWeather(id, obj) {
    $(".weather" + id + " .from").attr("src", obj.day_weather_pic);
    $(".weather" + id + " .to").attr("src", obj.night_weather_pic);
    $(".weather" + id + " .descr").html(obj.day_weather == obj.night_weather
        ? obj.day_weather : obj.day_weather + "转" + obj.night_weather);

}

'use strict';
const page = {

    init: null,
    initElement: null,
    initEvent: null,
    destroy: null,
    statistic: null,
    noticeDashboard: null,
    lastWeek:null,
    lastMonth:null,
    formatDate:null,
    addDate:null,
    setDate:null

};

page.init = function () {
    page.destroy();
    // this.weather();

    var loginCustomerId = $("#_loginCustomerId").val();
    var loginAccountId = $("#_loginAccountId").val();
    var loginVendorId = $("#_loginVendorId").val();
    if ((loginCustomerId != null && loginCustomerId != "")
        || (loginVendorId != null && loginVendorId != "")) {

       /* var optionUrl = "/api/c666378c5d3b417d8e150c456a489d23@accountId=" + loginAccountId;
        var ajaxType = "get"
        var optionParam = '{"properties":{}}'
        $("#customer_select").attr("optionUrl", optionUrl)
            .attr("ajaxType", ajaxType)
            .attr("optionParam", optionParam);*/

        let _this = $("#customer_select");
        Dolphin.ajax({
            url: '/api/c666378c5d3b417d8e150c456a489d23@accountId=' + loginAccountId,
            type: Dolphin.requestMethod.GET,
            async : false,
            // data: Dolphin.json2string({properties : shopCondition}),
            onSuccess: function (reData) {
                _this.append(
                    '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                $.each(reData.rows,function(index,obj){
                    _this.append(
                        '<option value="' + obj.id + '">'
                        + obj.name + '</option>');
                });
            }
        });
        $(".js-example-basic-single").select2();


    } else {
        /*var optionUrl = "/api/742445c653654caaa4a1fa69eb651a9a"
        var ajaxType = "post"
        var optionParam = '{"properties":{"category":"1"}}';
        $("#customer_select").attr("optionUrl", optionUrl)
            .attr("ajaxType", ajaxType)
            .attr("optionParam", optionParam);*/

        let _this = $("#customer_select");
        Dolphin.ajax({
            url: '/api/742445c653654caaa4a1fa69eb651a9a',
            type: Dolphin.requestMethod.POST,
            async : false,
            data: Dolphin.json2string({properties : {"category":"1"}}),
            onSuccess: function (reData) {
                _this.append(
                    '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                $.each(reData.rows,function(index,obj){
                    _this.append(
                        '<option value="' + obj.id + '">'
                        + obj.name + '</option>');
                });
            }
        });
        $(".js-example-basic-single").select2();
    }

    Dolphin.form.parse();

    page.initEvent();
    /*var shopCondition = {"selectCustomerId": loginCustomerId};
    if (loginCustomerId != null && loginCustomerId != "") {
        var _this = $("#shop_select");
        Dolphin.ajax({
            url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
            type: Dolphin.requestMethod.POST,
            async: false,
            data: Dolphin.json2string({properties: shopCondition}),
            onSuccess: function (reData) {
                $.each(reData.rows, function (index, obj) {
                    _this.append(
                        '<option value="' + obj.id + '">'
                        + obj.name + '</option>');
                });
            }
        });
    }
    $(".js-example-basic-multiple").select2();*/
    page.statistic();
    page.noticeDashboard("");
};

page.noticeDashboard = function () {
    const thisPage = this;

    $('#noticeDashboard').empty();
    return new Dolphin.LIST({
        panel: '#noticeDashboard',
        ajaxType: Dolphin.requestMethod.POST,
        // queryParams: {
        //     model_code_obj_ae: 'systemNotice'
        // },
        url: '/api/c97b00aa70fc4ed1b5922bced4468a0b',
        idField: 'id',
        columns: [{
            code: 'name',
            title: Dolphin.i18n.get("homepage.theTheme"),
            width: '170px'
        }, {
            code: 'remark',
            title: Dolphin.i18n.get("homepage.theContents")
        }, {
            code: 'createdDate',
            title: Dolphin.i18n.get("homepage.timeOfFoundation"),
            width: '110px'
        }, {
            code: 'createBy',
            title: Dolphin.i18n.get("homepage.theFounder"),
            width: '110px'
        }],
        multiple: false,
        pagination: false,
        checkbox: false,
        onLoadSuccess: function () {
            $('.editBtn').click(function () {
                let el = $(this);
                Dolphin.form.setValue(el.data(), '.stock-reassign-form');
                $('#stockModal_win').modal('show');
            });
        }
    });

};

page.initEvent = function () {
    const thisPage = this;

    //仅测试接收数据
    /*Dolphin.ajax({
        url: '/api/579e72dde170433ea0b4b333e5113842',
        type: Dolphin.requestMethod.POST,
        data: Dolphin.json2string({'cmd' : 'cache' , 'flag' : '0E1E' , 'status' : '01011E61A19800EE0E4700019811','data':'[1106140A0500000200000002000000142E, 1106140A0A00000500000005000000925E]','count':'0002',temp: 'A8C','Tend':'nnnnnnnnnnnnnnnnnnT'}),
        onSuccess: function (reData) {
            alert(reData);
        }
    });*/

    //选择客户
    $("#customer_select").change(function () {
        $("#shop_select").empty();
        var queryConditionObj = {};
        queryConditionObj.selectCustomerId = $(this).val();
        queryConditionObj.selectShopType = $("#shopType").val();
        var _this = $("#shop_select");

        Dolphin.ajax({
            url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
            type: Dolphin.requestMethod.POST,
            async: false,
            data: Dolphin.json2string({properties: queryConditionObj}),
            onSuccess: function (reData) {
                $.each(reData.rows, function (index, obj) {
                    _this.append(
                        '<option value="' + obj.id + '">'
                        + obj.name + '</option>');
                });
            }
        });

    });

    //选择门店类型
    $("#shopType").change(function () {

        $("#shop_select").empty();

        var queryConditionObj = {};
        queryConditionObj.selectCustomerId = $("#customer_select").val();
        queryConditionObj.selectShopType = $(this).val();

        var _this = $("#shop_select");

        Dolphin.ajax({
            url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
            type: Dolphin.requestMethod.POST,
            async: false,
            data: Dolphin.json2string({properties: queryConditionObj}),
            onSuccess: function (reData) {

                $.each(reData.rows, function (index, obj) {
                    _this.append(
                        '<option value="' + obj.id + '">'
                        + obj.name + '</option>');
                });

            }
        });

    });

    //查询
    $(".btn-query").click(function () {
        var shopIds = $('#shopIds').val();//默认根据登录帐号查找出旗下所有店铺
        var shopsCondition = $(".shop_array").val();//查询条件 店铺
        var shopTypeCondition = $("#shopType").val();//查询条件 店铺类型
        var shopAreaCondition = $("#customer_select").val();//查询条件 区域
        var barWidth = '60%';
        if (shopsCondition != null && shopsCondition.length > 0) {
            shopIds = shopsCondition.join("-");
            // if(shopsCondition.length<3)
            //     barWidth = '10%';
        } else if ((shopTypeCondition != null && shopTypeCondition.length > 0)
            || (shopAreaCondition != null && shopAreaCondition.length > 0)) {
            Dolphin.ajax({
                url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                type: Dolphin.requestMethod.POST,
                data: Dolphin.json2string({
                    properties: {
                        "selectCustomerId": shopAreaCondition,
                        "selectShopType": shopTypeCondition
                    }
                }),
                async: false,
                loading: true,
                onSuccess: function (reData) {
                    shopIds = '';
                    if (reData.rows) {
                        var shopIdArray = $.map(reData.rows, function (n) {
                            return n.id;
                        });
                        shopIds = shopIdArray.join('-');
                    }
                }
            });
        }
        var ddd = {  "dateType": $('#dateTypeVal').val(), "shopIdsStr": shopIds, "offsetDay": 0};
        if (ddd.dateType == 1) {
            ddd.offsetDay = 1;
        } else if(ddd.dateType == 0){
            ddd.offsetDay = 0;
        }

        Dolphin.ajax({
            url: '/api/783f76c9bb0348c28df1eea5c7a648e0',
            type: Dolphin.requestMethod.POST,
            data: Dolphin.json2string({properties: ddd}),
            loading: true,
            onSuccess: function (reData) {
                let prop = reData.value.properties;
                // $('#allCollectCount').html(prop.totalDxin);
                if(prop.shopTotal < 5){
                    barWidth = '10%';
                }

                if(prop.shopTotal > 15){
                    $("#shopsChart").css('height', (prop.shopTotal * 30)+'px');
                }else{
                    $("#shopsChart").css('height','460px');
                }
                // $.each(prop.shopIds, function (n, value) {
                //     let s = value.split("=");
                //     $("#shopSelect").append('<option value="' + s[0] + '">' + s[1] + '</option>');
                // });
                //
                // $("#shopSelect").change();
                // 基于准备好的dom，初始化echarts实例
                var shopsChart = echarts.init(document.getElementById('shopsChart'));
                // 指定图表的配置项和数据
                var shopsChartOption = {
                    color: ['#3398DB'],
                    title: {
                        text:Dolphin.i18n.get("homepage.distribution") + '['+(prop.shopTotal || 0)+']'
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        }
                    },
                    toolbox: {
                        feature: {
                            saveAsImage: {}
                        }
                    },
                    xAxis:
                        {
                            position : 'top',
                            type: 'value',
                            boundaryGap: [0, 0.01]
                        }
                    ,
                    yAxis:
                        {
                            type: 'category',
                            axisLabel:{
                                interval:0//横轴信息全部显示
                            },
                            data: []
                        }
                    ,
                    series: [
                        {
                            name: '客流量',
                            type: 'bar',
                            barWidth : barWidth,
                            label: {
                                normal: {
                                    show: true,
                                    position: 'right'
                                }
                            },
                            data: []
                        }
                    ]
                };
                shopsChartOption.yAxis.data = prop.chartNames;
                shopsChartOption.series[0].data = prop.chartDatas;

                shopsChart.setOption(shopsChartOption, true);
            }
        });
    });

    //点击时间维度按钮
    $(".btn_date").click(function () {
        $(".btn_select").removeClass('btn_select').addClass('btn_unselect');
        $(this).removeClass('btn_unselect').addClass('btn_select');
        var dateVal = $(this).data('type');
        $("#dateTypeVal").val(dateVal);
        // thisPage.showCharts();
        $(".btn-query").click();
    });
};

page.destroy = function () {

};

page.showCharts = function () {
    const thisPage = this;
    Dolphin.ajax({
        url: '/api/783f76c9bb0348c28df1eea5c7a648e0',
        type: Dolphin.requestMethod.POST,
        data: Dolphin.json2string({
            properties: {
                "dateType": $('#dateTypeVal').val(),
                "shopIdsStr": $('#shopIds').val(),
                "offsetDay":0
            }
        }),
        loading: true,
        onSuccess: function (reData) {
            let prop = reData.value.properties;

            // $.each(prop.shopIds, function (n, value) {
            //     let s = value.split("=");
            //     $("#shopSelect").append('<option value="' + s[0] + '">' + s[1] + '</option>');
            // });
            //
            $("#shopSelect").change();
            if(prop.shopTotal > 15){
                $("#shopsChart").css('height', (prop.shopTotal * 30)+'px');
            }else{
                $("#shopsChart").css('height','460px');
            }

            // 基于准备好的dom，初始化echarts实例
            var shopsChart = echarts.init(document.getElementById('shopsChart'));
            // 指定图表的配置项和数据
            var shopsChartOption = {
                color: ['#3398DB'],
                title: {
                    text: Dolphin.i18n.get("homepage.distribution")+'['+(prop.shopTotal || 0)+']'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    position : 'top',
                    type: 'value',
                    boundaryGap: [0, 0.01]

                },
                yAxis: {
                    type: 'category',
                    axisLabel:{
                        interval:0//横轴信息全部显示
                    },
                    data: []
                },
                series: [
                    {
                        name: Dolphin.i18n.get("homepage.distribution"),
                        type: 'bar',
                        barWidth : '60%',
                        label: {
                            normal: {
                                show: true,
                                position: 'right'
                            }
                        },
                        data: []
                    }
                ]
            };
            shopsChartOption.yAxis.data = prop.chartNames;
            shopsChartOption.series[0].data = prop.chartDatas;

            shopsChart.setOption(shopsChartOption);
        }
    });

};

page.statistic = function () {
    const thisPage = this;

    $('body > #loading').show(function(){
        Dolphin.ajax({
            url: '/api/65e7adad33f14f8e8c6454783125bcf1@accountId=' + org.breezee.context.userData.userId,
            type: Dolphin.requestMethod.GET,
            onSuccess: function (reData) {
                let prop = reData.value.properties;
                $('#allShop').html(prop.shopSize);
                $('#allDevice').html(prop.deviceSize);
                $('#exDevice').html(prop.exDeviceSize);
                $('#shopIds').val(prop.shopIdsStr);
                $('#allCollectCount').html(prop.totalDxin);
                $('body > #loading').hide();
                thisPage.showCharts();
                // $.each(prop.shopIds, function (n, value) {
                //     let s = value.split("=");
                //     $("#shopSelect").append('<option value="' + s[0] + '">' + s[1] + '</option>');
                // });
                //
                // $("#shopSelect").change();
            }
        });
    });

    // $('#planEndDate').html('2099-01-01');
    $(".js-example-basic-single").select2();
};

$(function () {

    org.breezee.menu.topSelect('index');
    page.init();

    // org.breezee.page = {
    //     weather: function(){
    //         Dolphin.ajax({
    //             url: '/api/c1c13d80a220448bb83c2209319707c1' ,
    //             type: Dolphin.requestMethod.POST,
    //             onSuccess: function (reData) {
    //                 console.log(reData);
    //                 showWeather("F1",reData.extProps.showapi_res_body.f1);
    //                 $(".weatherF1 .day").html(reData.extProps.showapi_res_body.f1.day.substr(6,2) + "日(今天)");
    //
    //                 showWeather("F2",reData.extProps.showapi_res_body.f2);
    //                 $(".weatherF2 .day").html(reData.extProps.showapi_res_body.f2.day.substr(6,2) + "日(明天)");
    //
    //                 showWeather("F3",reData.extProps.showapi_res_body.f3);
    //                 $(".weatherF3 .day").html(reData.extProps.showapi_res_body.f3.day.substr(6,2) + "日(后天)");
    //
    //                 showWeather("F4",reData.extProps.showapi_res_body.f4);
    //                 $(".weatherF4 .day").html(reData.extProps.showapi_res_body.f4.day.substr(6,2) + "日("
    //                     +showWeek(reData.extProps.showapi_res_body.f4.weekday)+")");
    //
    //                 showWeather("F5",reData.extProps.showapi_res_body.f5);
    //                 $(".weatherF5 .day").html(reData.extProps.showapi_res_body.f5.day.substr(6,2) + "日("
    //                     +showWeek(reData.extProps.showapi_res_body.f5.weekday)+")");
    //
    //                 showWeather("F6",reData.extProps.showapi_res_body.f6);
    //                 $(".weatherF6 .day").html(reData.extProps.showapi_res_body.f6.day.substr(6,2) + "日("
    //                     +showWeek(reData.extProps.showapi_res_body.f6.weekday)+")");
    //
    //                 showWeather("F7",reData.extProps.showapi_res_body.f7);
    //                 $(".weatherF7 .day").html(reData.extProps.showapi_res_body.f7.day.substr(6,2) + "日("
    //                     +showWeek(reData.extProps.showapi_res_body.f7.weekday)+")");
    //             }
    //         });
    //     },
    // };
    // org.breezee.page.init();

});

page.formatDate = function(date){
    let year = date.getFullYear()+'-';
    let month = (date.getMonth()+1)+'-';
    let day = date.getDate();

    return year+month+day;
};
page.addDate= function(date,n){
    date.setDate(date.getDate()+n);
    return date;
};
page.setDate = function(date){

    $("#lastWeekHint").html(page.formatDate(date)+"----"+page.formatDate(page.addDate(date,6)));
};

/**
 * 获得上周开始日期和结束日期
 * 周日----周六
 */
page.lastWeek = function () {
    var date = new Date();
    var week = date.getDay();
    date = page.addDate( date,week*-1); //本周第一天 周日
    page.setDate(page.addDate(date,-7));//上周
}

/**
 * 获得上月开始日期和结束日期
 * 月初----周末
 */
page.lastMonth = function () {
    var now = new Date(); //当前日期
    var nowYear = now.getYear(); //当前年
    nowYear += (nowYear < 2000) ? 1900 : 0; //

    var lastMonthDate = new Date(); //上月日期
    lastMonthDate.setDate(1);
    lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
    var lastMonth = lastMonthDate.getMonth();

    var lastMonthStartDate = new Date(nowYear, lastMonth, 1);//上月开始时间

    //获得上月天数
    var monthStartDate = new Date(nowYear, lastMonth, 1);
    var monthEndDate = new Date(nowYear, lastMonth + 1, 1);
    var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);

    var lastMonthEndDate = new Date(nowYear, lastMonth, days);//上月结束时间


    $("#lastMonthHint").html(page.formatDate(lastMonthStartDate)+"----"+page.formatDate(lastMonthEndDate));
}
$("#lastMonthBtn").mouseover(function () {
    page.lastMonth();
    $("#lastMonthHint").removeClass("hidden");
    $("#lastMonthHint").addClass("show");

});
$("#lastMonthBtn").mouseout(function () {
    $("#lastMonthHint").removeClass("show");
    $("#lastMonthHint").addClass("hidden");

});
$("#lastWeekBtn").mouseover(function () {
    page.lastWeek();
    $("#lastWeekHint").removeClass("hidden");
    $("#lastWeekHint").addClass("show");

});
$("#lastWeekBtn").mouseout(function () {
    $("#lastWeekHint").removeClass("show");
    $("#lastWeekHint").addClass("hidden");
});


